package com.ple.app.importdata;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.ple.app.jzsf.R;
import com.ple.app.sevlet.GetFromServer;
import com.ple.app.sevlet.GetIdList;
import com.ple.app.sevlet.JsonTools;
import com.ple.app.sevlet.NetConnect;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Soilpoint_Activity extends Activity {

    private ListView listView;
    private TextView add_point;
    private EditText text_lon;
    private EditText text_lat;
    private EditText text_n;
    private EditText text_p;
    private EditText text_k;
    private EditText text_ph;
    private EditText text_or;
    private Button save_soildata;
    private String opreat_id;
    private String dk;
    private TextView location;
    private EditText distance;
    private final String[] list_content = {"ID", "lon", "lat", "N", "P", "K", "PH", "organic", "name", "DK"};
    private LocationManager locationManager;//位置信息
    private String locationprovider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_soilpoint);
        listView = (ListView) findViewById(R.id.point_data);
        add_point = (TextView) findViewById(R.id.add_point);
        text_lon = (EditText) findViewById(R.id.text_lon);
        text_lat = (EditText) findViewById(R.id.text_lat);
        text_n = (EditText) findViewById(R.id.text_n);
        text_k = (EditText) findViewById(R.id.text_k);
        text_p = (EditText) findViewById(R.id.text_p);
        text_ph = (EditText) findViewById(R.id.text_ph);
        text_or = (EditText) findViewById(R.id.text_or);
        save_soildata = (Button) findViewById(R.id.save_soildata);
        location = (TextView) findViewById(R.id.location);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        dk = bundle.getString("DK");
        inidata();
        updatalistview();
    }//oncreat

    private void inidata() {
        if(NetConnect.isNetworkAvailable(Soilpoint_Activity.this))update();
        /**
         * 添加采样点
         */
        add_point.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                LayoutInflater a = LayoutInflater.from(Soilpoint_Activity.this);
                final View dialogview = a.inflate(R.layout.point_name, null);
                final EditText name = (EditText) dialogview.findViewById(R.id.point_name);
                new AlertDialog.Builder(Soilpoint_Activity.this).setTitle("请输入采样点名：")
                        .setView(dialogview).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (name.getText().toString().equals("")) {
                            Toast.makeText(getApplicationContext(), "采样点名不能为空！", Toast.LENGTH_LONG).show();
                        } else {
                            //String[] list_content={"ID","lon","lat","N","P","K","name","DK"};
                            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                            MyopenHelper myopenhelper = new MyopenHelper(Soilpoint_Activity.this, "seed.db", null, 1);
                            SQLiteDatabase db = myopenhelper.getReadableDatabase();
                            ContentValues values = new ContentValues();
                            Cursor curor_getid = db.query("soildata", list_content, null, null, null, null, null, null);
                            String curor_id = "0";
                            if (curor_getid.getCount() != 0 && curor_getid.moveToLast())
                                curor_id = curor_getid.getString(0);
                            else {
                                curor_id = "0";
                            }
                            curor_getid.close();
                            int id = 1 + Integer.valueOf(curor_id);
                            values.put("ID", id);
                            values.put("lon", "");
                            values.put("lat", "");
                            values.put("N", "");
                            values.put("P", "");
                            values.put("K", "");
                            values.put("PH", "");
                            values.put("organic", "");
                            values.put("name", name.getText().toString());
                            values.put("DK", dk);

                            db.insert("soildata", null, values);
                            db.close();
                            updatalistview();
                        }
                    }
                }).setNegativeButton("取消", null).show();
            }
        });

        /**
         * list添加事件
         */
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // String[] list_content={"ID","lon","lat","N","P","K","name","DK"};
                HashMap<String, String> getmap = (HashMap<String, String>) listView.getItemAtPosition(position);
                opreat_id = getmap.get("ID");
                String[] args = new String[]{opreat_id};
                MyopenHelper myopenhelper = new MyopenHelper(Soilpoint_Activity.this, "seed.db", null, 1);
                SQLiteDatabase db = myopenhelper.getReadableDatabase();
                Cursor curor = db.query("soildata", list_content, "ID=?", args, null, null, null, null);
                //Cursor curor = db.query("seed", conlm, "ID=?", args, null, null, null, null);
                //刚开始是指向第一个的前一个的
                //String str=String.valueOf(curor.getCount());
                //text_lat.setText(str);
                if (curor.moveToFirst()) {
                    String lon = curor.getString(1);
                    String lat = curor.getString(2);
                    String n = curor.getString(3);
                    String p = curor.getString(4);
                    String k = curor.getString(5);
                    String ph = curor.getString(6);
                    String orgiac = curor.getString(7);
                    text_lon.setText(lon);
                    text_lat.setText(lat);
                    text_n.setText(n);
                    text_p.setText(p);
                    text_k.setText(k);
                    text_ph.setText(ph);
                    text_or.setText(orgiac);
                } else {
                    Toast.makeText(getApplicationContext(), "没找到相关数据！", Toast.LENGTH_LONG).show();
                }
                curor.close();
                db.close();

            }
        });
        /**
         * 保存修改
         */
        save_soildata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] args = new String[]{opreat_id};
                MyopenHelper myopenhelper = new MyopenHelper(Soilpoint_Activity.this, "seed.db", null, 1);
                SQLiteDatabase db = myopenhelper.getReadableDatabase();
                ContentValues values = new ContentValues();
                values.put("lon", text_lon.getText().toString());
                values.put("lat", text_lat.getText().toString());
                values.put("N", text_n.getText().toString());
                values.put("P", text_p.getText().toString());
                values.put("K", text_k.getText().toString());
                values.put("PH", text_ph.getText().toString());
                values.put("organic", text_or.getText().toString());
                db.update("soildata", values, "ID=?", args);
                db.close();
                if(NetConnect.isNetworkAvailable(Soilpoint_Activity.this))toserver();//修改服务端
                Toast.makeText(getApplicationContext(), "数据修改成功！", Toast.LENGTH_LONG).show();
            }
        });

        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                List<String> provider = locationManager.getProviders(true);
                LocationListener locationListener=new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {

                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {

                    }

                    @Override
                    public void onProviderEnabled(String provider) {

                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                    }

                };
                if (ActivityCompat.checkSelfPermission(Soilpoint_Activity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Soilpoint_Activity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                   return;
                }else{
                    if (provider.contains(LocationManager.GPS_PROVIDER)) {
                        locationprovider = LocationManager.GPS_PROVIDER;
                        //Toast.makeText(getApplicationContext(), locationprovider, Toast.LENGTH_LONG).show();
                    } else if (provider.contains(LocationManager.NETWORK_PROVIDER)) {
                        locationprovider = LocationManager.NETWORK_PROVIDER;
                        //Toast.makeText(getApplicationContext(), locationprovider, Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(getApplicationContext(), "没有可用的位置信息！", Toast.LENGTH_LONG).show();
                        return;
                    }
                    locationManager.requestLocationUpdates(locationprovider,1000,0, locationListener);
                    Location location1 = locationManager.getLastKnownLocation(locationprovider);

                if(location1!=null){
                    double longitude=location1.getLongitude();
                    double latitude=location1.getLatitude();
                    text_lon.setText(String.valueOf(longitude));
                    text_lat.setText(String.valueOf(latitude));
                }else{
                    Toast.makeText(getApplicationContext(), "无法获得当前位置信息！", Toast.LENGTH_LONG).show();
                }
                }

            }
        });
    }
    /**
     * 更新Listview
     */
    private void updatalistview(){
        String[] args=new String[]{dk};
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        //String[] list_content={"ID","lon","lat","N","P","K","name","DK"};
        MyopenHelper myopenhelper=new MyopenHelper(Soilpoint_Activity.this,"seed.db",null,1);
        SQLiteDatabase db=myopenhelper.getReadableDatabase();
        Cursor curor=db.query("soildata",list_content,"DK=?",args,null,null,null,null);
            while (curor.moveToNext()){
                Map<String, Object> item1 = new HashMap<String, Object>();
                String name=curor.getString(8);
                String ID=curor.getString(0);
                item1.put("ID",ID);
                item1.put("name", name);
                list.add(item1);}
        curor.close();
        db.close();
        SimpleAdapter adapter = new SimpleAdapter(Soilpoint_Activity.this, list, R.layout.soildataitem,
                new String[]{"ID","name"},
                new int[]{R.id.poingid,R.id.pointname});
        listView.setAdapter(adapter);
    }
    /**
     * 从服务端获得数据
     */
    private void update(){
        final Handler myHandler=new Handler() {
            @Override
            public void handleMessage(Message msg) {
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                List<Map<String, Object>> list_c = new ArrayList<Map<String, Object>>();
                String rponse= (String) msg.obj;
                if(rponse.isEmpty()){}
                else if(rponse.equals("1")){
                    //Toast.makeText(getApplicationContext(),"同步完成",Toast.LENGTH_LONG).show();
                }
                else{
                    list= JsonTools.getListmap("data",rponse);//获得服务器传来的数据
                    int size=list.size();
                    MyopenHelper myopenhelper = new MyopenHelper(Soilpoint_Activity.this, "seed.db", null, 1);
                    SQLiteDatabase db = myopenhelper.getReadableDatabase();
                    // Log.i("input", "同步");
                    for(int i=0;i<size;i++){
                        Map<String, Object> item = new HashMap<String, Object>();
                        item= list.get(i);
                        String id= String.valueOf(item.get("id"));
                        String lon= String.valueOf(item.get("lon"));
                        String lat= String.valueOf(item.get("lat"));
                        String n= String.valueOf(item.get("n"));
                        String p= String.valueOf(item.get("p"));
                        String k= String.valueOf(item.get("k"));
                        String ph= String.valueOf(item.get("ph"));
                        String organic= String.valueOf(item.get("organic"));
                        String name= String.valueOf(item.get("name"));
                        String dk= String.valueOf(item.get("dk"));
                        /**
                         * 同步到本地
                         */
                        ContentValues values = new ContentValues();
                        values.put("ID", id);
                        values.put("lon", lon);
                        values.put("lat", lat);
                        values.put("N", n);
                        values.put("P", p);
                        values.put("K", k);
                        values.put("PH", ph);
                        values.put("organic",organic);
                        values.put("name", name);
                        values.put("DK", dk);
                        db.insert("soildata", null, values);
                    }// while(iterator.hasNext())
                    db.close();
                    updatalistview();
                    final String jsonstring= GetIdList.DBofsoilToServer(Soilpoint_Activity.this,rponse);
                    if(jsonstring.equals("0")){}
                    else{
                        //Log.i("input", "第2次线程");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                GetFromServer getfromserver=new GetFromServer();
                                getfromserver.postDB(jsonstring,getfromserver.soil_url);
                            }
                        }).start();}

                }//else
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                String jsonstring=GetIdList.getAllidFromTB(Soilpoint_Activity.this,"soildata");
                GetFromServer getfromserver=new GetFromServer();
                String result=getfromserver.dopost(jsonstring,null,getfromserver.soil_url);
                Message msg=new Message();
                msg.obj=result;
                myHandler.sendMessage(msg);
            }
        }).start();
    }
    /**
     * 同步修改到服务端
     */
    private void toserver(){
        List<Map<String, Object>> listS = new ArrayList<Map<String, Object>>();
        String[] args = new String[]{opreat_id};
        String[] conlm=new String[]{"ID","lon","lat","N","P","K","PH","organic","name","DK"};
        MyopenHelper myopenhelper=new MyopenHelper(Soilpoint_Activity.this,"seed.db",null,1);
        SQLiteDatabase db=myopenhelper.getReadableDatabase();
            Cursor curor=db.query("soildata",conlm,"ID=?",args,null,null,null,null);
            while(curor.moveToNext()){
                Map<String, Object> item = new HashMap<String, Object>();
                String id1 = curor.getString(0);
                String lon = curor.getString(1);
                String lat=curor.getString(2);
                String n = curor.getString(3);
                String p = curor.getString(4);
                String k=curor.getString(5);
                String ph=curor.getString(6);
                String organic=curor.getString(7);
                String name = curor.getString(8);
                String dk=curor.getString(9);
                item.put("id", id1);
                item.put("lon", lon);
                item.put("lat", lat);
                item.put("n", n);
                item.put("p", p);
                item.put("k", k);
                item.put("ph", ph);
                item.put("organic", organic);
                item.put("name", name);
                item.put("dk", dk);
                listS.add(item);
            }
            curor.close();

        db.close();
        JSONObject object=new JSONObject();
        try {
            object.put("data",listS);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        final String js=object.toString();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    GetFromServer getfromserver=new GetFromServer();
                    getfromserver.postDB(js,getfromserver.soilup_url);
                }
            }).start();
    }
}
